<template>
  <div class="carousel-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>轮播图管理</h2>
      <p>管理智慧医疗系统首页轮播图，包括图片上传、标题设置、链接配置等功能</p>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-container">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="标题:">
          <el-input
            v-model="searchForm.title"
            placeholder="输入标题或关键字"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="上传时间:">
          <el-date-picker
            v-model="searchForm.startTime"
            type="date"
            placeholder="开始时间"
            style="width: 160px"
          />
        </el-form-item>
        
        <el-form-item label="结束时间:">
          <el-date-picker
            v-model="searchForm.endTime"
            type="date"
            placeholder="结束时间"
            style="width: 160px"
          />
        </el-form-item>
        
        <el-form-item>
          <div class="button-group">
            <el-button type="primary" :icon="Search" @click="handleSearch">
              筛选
            </el-button>
            <el-button :icon="Refresh" @click="handleReset">
              重置
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- 轮播图列表 -->
    <div class="card-container" style="overflow-x: auto;">
      <div class="table-header">
        <h3>轮播图列表</h3>
        <div class="header-actions">
          <el-button type="primary" :icon="Plus" @click="handleAddPage">
            新增轮播图
          </el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        @selection-change="handleSelectionChange"
        table-layout="fixed"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="title" label="轮播图标题" min-width="200">
          <template #default="{ row }">
            <div class="title-cell">
              <span class="title-text">{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="image" label="缩略图" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              class="carousel-thumbnail"
              fit="cover"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '上架' ? 'success' : 'info'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="uploader" label="上传人" width="120" />
        
        <el-table-column prop="uploadTime" label="上传时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.uploadTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-space wrap>
              <el-button
                type="primary"
                :icon="Edit"
                size="small"
                @click="handleEditPage(row)"
              >
                编辑
              </el-button>
              
              <el-button
                type="danger"
                size="small"
                :loading="deleteLoading && currentDeleteId === row.id"
                @click="handleDelete(row)"
              >
                <template #icon>
                  <Delete />
                </template>
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-operations" v-if="selectedRows.length > 0">
        <span>已选择 {{ selectedRows.length }} 项</span>
        <el-button 
          type="danger" 
          :icon="Delete" 
          :loading="batchDeleteLoading"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 弹窗功能已移除 -->
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { carouselApi } from '@/api/index'
import type { CarouselItem, CarouselSearchParams } from '@/api/index'
import dayjs from 'dayjs'

/**
 * 智慧医疗系统 - 轮播图管理页面
 * 功能：轮播图的增删改查、图片上传、状态管理
 */

const router = useRouter()

// 接口类型定义
interface CarouselItem {
  id: number
  title: string
  imageUrl: string
  linkUrl?: string
  status: '上架' | '下架'
  uploader: string
  uploadTime: string
  sortOrder: number
  description?: string
  effectiveTime?: [string, string]
}

interface SearchForm {
  title: string
  startTime: string
  endTime: string
}

// 响应式数据
const loading = ref(false)
const selectedRows = ref<CarouselItem[]>([])
// 删除相关状态
const deleteLoading = ref(false)
const batchDeleteLoading = ref(false)
const currentDeleteId = ref<number | null>(null)

// 搜索表单
const searchForm = reactive<SearchForm>({
  title: '',
  startTime: '',
  endTime: ''
})

// 表格数据
const tableData = ref<CarouselItem[]>([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 生命周期
onMounted(() => {
  loadData()
})

// 方法
/**
 * 加载轮播图数据
 * @param resetPagination 是否重置分页
 */
const loadData = async (resetPagination = false) => {
  if (resetPagination) {
    pagination.currentPage = 1
  }
  
  loading.value = true
  try {
    const params: CarouselSearchParams = {
      title: searchForm.title,
      startTime: searchForm.startTime,
      endTime: searchForm.endTime,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const response = await carouselApi.getList(params)
    
    if (response.code === 200) {
      const data = response.data
      tableData.value = data.items.map(item => ({
        ...item,
        status: item.status === 1 ? '上架' : '下架',
        uploader: item.uploader || '系统管理员',
        uploadTime: item.uploadTime
      }))
      pagination.total = data.totalCount
      
      // 计算统计信息
      const stats = {
        total: data.totalCount,
        active: data.items.filter(item => item.status === 1).length,
        inactive: data.items.filter(item => item.status === 0).length
      }
      
      console.log('轮播图统计信息:', stats)
    } else {
      ElMessage.error('获取轮播图数据失败')
    }
  } catch (error) {
    console.error('加载轮播图数据出错:', error)
    ElMessage.error('加载轮播图数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    title: '',
    startTime: '',
    endTime: ''
  })
  handleSearch()
}

// 跳转到新增页面
const handleAddPage = () => {
  router.push('/content/carousel/add')
}

// 跳转到编辑页面
const handleEditPage = (row: CarouselItem) => {
  router.push(`/content/carousel/edit/${row.id}`)
}

/**
 * 删除单个轮播图
 * @param row 要删除的轮播图数据
 */
const handleDelete = async (row: CarouselItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除轮播图"${row.title}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        message: `
          <div style="margin: 10px 0;">
            <p style="margin: 0 0 10px 0; color: #606266;">轮播图信息：</p>
            <p style="margin: 0 0 5px 0;"><strong>标题：</strong>${row.title}</p>
            <p style="margin: 0 0 5px 0;"><strong>状态：</strong>${row.status}</p>
            <p style="margin: 0 0 5px 0;"><strong>上传时间：</strong>${formatDate(row.uploadTime)}</p>
            <p style="margin: 10px 0 0 0; color: #F56C6C; font-size: 14px;">
              <i class="el-icon-warning" style="margin-right: 5px;"></i>
              删除后将无法恢复，请谨慎操作！
            </p>
          </div>
        `
      }
    )
    
    // 设置当前删除ID和加载状态
    currentDeleteId.value = row.id
    deleteLoading.value = true
    
    const response = await carouselApi.delete(row.id!)
    
    if (response.code === 200) {
      ElMessage.success(`轮播图"${row.title}"删除成功`)
      await loadData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
    
  } catch (error) {
    // 用户取消删除或删除失败
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  } finally {
    deleteLoading.value = false
    currentDeleteId.value = null
  }
}


const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的项目')
    return
  }
  
  try {
    // 生成选中项目的详细信息
    const selectedInfo = selectedRows.value.map(item => 
      `• ${item.title} (${item.status})`
    ).join('<br/>')
    
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个轮播图吗？`,
      '批量删除确认',
      {
        confirmButtonText: `确定删除 ${selectedRows.value.length} 项`,
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
        message: `
          <div style="margin: 10px 0;">
            <p style="margin: 0 0 10px 0; color: #606266;">即将删除以下轮播图：</p>
            <div style="max-height: 200px; overflow-y: auto; background: #f8f9fa; padding: 10px; border-radius: 4px; margin: 10px 0;">
              ${selectedInfo}
            </div>
            <p style="margin: 10px 0 0 0; color: #F56C6C; font-size: 14px;">
              <i class="el-icon-warning" style="margin-right: 5px;"></i>
              批量删除后将无法恢复，请谨慎操作！
            </p>
          </div>
        `
      }
    )
    
    batchDeleteLoading.value = true
    
    const ids = selectedRows.value.map(item => item.id!).filter(id => id !== undefined)
    const response = await carouselApi.batchDelete(ids)
    
    if (response.code === 200) {
      ElMessage.success(`成功删除 ${ids.length} 个轮播图`)
      selectedRows.value = []
      await loadData()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请重试')
    }
  } finally {
    batchDeleteLoading.value = false
  }
}



// 分页相关
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  loadData()
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

/**
 * 处理表格选择变化
 * @param selection 选中的行数据
 */
const handleSelectionChange = (selection: CarouselItem[]) => {
  selectedRows.value = selection
}


</script>

<style lang="scss" scoped>
.carousel-management {
  .page-header {
    margin-bottom: 24px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    p {
      margin: 0;
      color: $text-color-regular;
      font-size: 14px;
    }
  }
  
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid $border-color-lighter;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .title-cell {
    .title-text {
      font-weight: 500;
      color: $text-color-primary;
    }
  }
  
  .carousel-thumbnail {
    width: 80px;
    height: 40px;
    border-radius: 4px;
    object-fit: cover;
  }
  
  .batch-operations {
    padding: 16px 20px;
    background-color: #f8f9fa;
    border-top: 1px solid $border-color-lighter;
    display: flex;
    justify-content: space-between;
    align-items: center;
    animation: slideDown 0.3s ease-in-out;
    
    span {
      color: $text-color-regular;
      font-size: 14px;
      font-weight: 500;
    }
    
    .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
      }
    }
  }
  
  .pagination-container {
    padding: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .upload-container {
    .image-uploader {
      .uploaded-image {
        width: 200px;
        height: 120px;
        object-fit: cover;
        border-radius: 8px;
        display: block;
        border: 1px solid $border-color;
      }
      
      .upload-placeholder {
        width: 200px;
        height: 120px;
        border: 2px dashed $border-color;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: border-color 0.3s;
        background-color: #fafafa;
        
        &:hover {
          border-color: $primary-color;
        }
        
        .upload-icon {
          font-size: 32px;
          color: $text-color-placeholder;
        }
        
        .upload-text {
          margin-top: 10px;
          font-size: 14px;
          color: $text-color-placeholder;
        }
      }
    }
    
    .upload-tips {
      margin-top: 8px;
      font-size: 12px;
      color: $text-color-secondary;
      line-height: 1.4;
    }
  }
  
  .sort-tips {
    margin-top: 8px;
    font-size: 12px;
    color: $text-color-secondary;
    line-height: 1.4;
  }
  
  .form-container {
    .el-form-item {
      margin-bottom: 24px;
      
      .el-form-item__label {
        font-weight: 500;
        color: $text-color-primary;
      }
    }
    
    .el-input-number {
      .el-input__inner {
        text-align: left;
      }
    }
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  // 动画效果
  @keyframes slideDown {
    from {
      opacity: 0;
      transform: translateY(-10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  // 操作按钮样式优化
  .action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    
    .el-button {
      transition: all 0.3s ease;
      font-size: 12px;
      
      &.is-loading {
        opacity: 0.7;
      }
      
      &--danger {
        &:not(.is-loading):hover {
          background-color: #f89898;
          border-color: #f89898;
          transform: translateY(-1px);
          box-shadow: 0 4px 8px rgba(245, 108, 108, 0.3);
        }
      }
      
      &--primary {
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
        }
      }
    }
  }
  
  // 保持原有的button-group样式用于其他地方
  .button-group {
    .el-button {
      transition: all 0.3s ease;
      
      &.is-loading {
        opacity: 0.7;
      }
      
      &--danger {
        &:not(.is-loading):hover {
          background-color: #f89898;
          border-color: #f89898;
          transform: translateY(-1px);
          box-shadow: 0 4px 8px rgba(245, 108, 108, 0.3);
        }
      }
    }
  }
}
</style>